package cn.codergege.myspider.Event;

import cn.codergege.myspider.config.Config;

import java.util.*;
import java.util.function.Consumer;

public class EventManager {
    private static final Map<Event, List<Consumer<Config>>> eventConsumerMap = new LinkedHashMap<>();
    public static void registerEvent(Event event, Consumer<Config> consumer) {
        List<Consumer<Config>> consumers = getConsumners(event);
        if(null == eventConsumerMap) {
            consumers = new ArrayList<>();
        }
        consumers.add(consumer);
        eventConsumerMap.put(event, consumers);
    }

    public static void fireEvent(Event event, Config config) {
        Optional.ofNullable(eventConsumerMap.get(event)) // 如果存在
                .ifPresent(
                        consumers -> { // 处理 consumers
                            consumers.forEach(consumer -> consumer.accept(config));
                        }
                );
    }

    private static List<Consumer<Config>> getConsumners(Event event) {
        return eventConsumerMap.get(event);
    }
}
